import Vue from 'vue';
import App from './App';
import router from './router';
import axios from 'axios';
import ElementUI from 'element-ui';
import store from './store'
import 'element-ui/lib/theme-chalk/index.css';    // 默认主题
import "babel-polyfill";
import VueParticles from 'vue-particles'  
import _ from 'underscore'
import VueMqtt from 'vue-mqtt'
Vue.use(VueMqtt, 'ws://112.74.38.244:61623/mqtt', {username:'admin',password:'password',clientId: 'WebClient-' + '123456'})
Vue.use(ElementUI, { size: 'small' });
Vue.use(VueParticles)  
// http response 拦截器
axios.interceptors.response.use(
    response => {
        var flag=_.indexOf([10002,10001],response.data.errcode)
        //不等于-1就代表没匹配到，是合法的token,匹配到了就代表这个token是非法的
        if(flag!=-1){
            store.commit('setUserName','')
            localStorage.removeItem('token')
            localStorage.removeItem('username')
            router.replace({
                path: 'login',
            })
            location.reload()
        }
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    }
);
Vue.prototype.$http = axios;
router.beforeEach((to, from, next) => {
    const role = localStorage.getItem('token');
    var path=to.path.split('/')[1]
    var flag=_.indexOf(['index','login','api'],path)
      if(path=='open'){
        store.commit('setNavActiveIndex',2)
      }else if(path=='index'){
        store.commit('setNavActiveIndex',1)
      }else if(path=='api'){
        store.commit('setNavActiveIndex',3)
      }
    if(!role && flag == -1){
        next('/login');
    }else if(to.meta.permission){
        // 如果是管理员权限则可进入，这里只是简单的模拟管理员权限而已
        role === 'admin' ? next() : next('/403');
    }else{
        // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
        if(navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor'){
            Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
                confirmButtonText: '确定'
            });
        }else{
            next();
        }
    }
})

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');